﻿using FirstDemo.Attr;
using FirstDemo.Common;
using FirstDemo.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Postal;
using Postal.AspNetCore;
using RabbitMQ.Client;
using System.Text;
using System.Threading.Tasks;
using TestWebService;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace FirstDemo.Controllers
{
    [Route("api/[controller]/[action]")]
    public class TestController : Controller
    {
        private readonly IEmailService _emailService;
        private readonly EmailServiceOptions _emailServiceOptions;

        //static int _callCount;
        private readonly IHttpContextAccessor _httpContextAccessor;
        //private readonly ILogger<TestController> _logger;
        //private readonly IDiagnosticContext _diagnosticContext;
        private CoreTestSoap _webService;

        public TestController(ILogger<TestController> logger,
            IHttpContextAccessor httpContextAccessor,
            CoreTestSoap service, IEmailService emailService,
            IOptions<EmailServiceOptions> o)//, IDiagnosticContext diagnosticContext
        {
            _emailService = emailService;
            _emailServiceOptions = o.Value;

            _httpContextAccessor = httpContextAccessor;
            _webService = service;
            //_logger = logger ?? throw new ArgumentNullException(nameof(logger));
            //_diagnosticContext = diagnosticContext ?? throw new ArgumentNullException(nameof(diagnosticContext));
        }

        /// <summary>
        /// 测试MD5加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        [HttpGet]
        public string MD5(string str)
        {
            string temp = EncryptHelper.MD5Encrypt(str);
            return temp + "  " + temp.Length;
        }

        /// <summary>
        /// 测试AES加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        [HttpGet]
        public string AesEn(string str)
        {
            string temp = EncryptHelper.AESEncrypt(str, "Lesan");
            return temp + "  " + temp.Length;
        }

        /// <summary>
        /// 测试AES解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        [HttpGet]
        public string AesDe(string str)
        {
            string temp = EncryptHelper.AESDecrypt(str, "Lesan");
            return temp + "  " + temp.Length;
        }

        /// <summary>
        /// 测试日志输出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Log()
        {
            HttpContext.Items.Add("Message", "测试日志");

            //Serilog测试
            //_logger.LogInformation("Hello, world!");
            //_diagnosticContext.Set("IndexCallCount", Interlocked.Increment(ref _callCount));

            //log4net测试
            //LogHelper.Info("Hello World!");

            //var piList = typeof(TestController).GetProperties();

            return Ok(JsonConvert.SerializeObject(""));
        }

        /// <summary>
        /// 测试WebService
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string WebService()
        {
            var result1 = _webService.HelloWorldAsync(new HelloWorldRequest()).Result.Body.HelloWorldResult;
            var result2 = _webService.TestMethodAsync(new TestMethodRequest(new TestMethodRequestBody("测试TestMethod方法"))).Result.Body.TestMethodResult;
            var result3 = _webService.AddAsync(1, 2).Result.ToString();
            return result1 + " " + result2 + " " + result3;
        }

        /// <summary>
        /// 测试返回数据封装
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string Result()
        {
            return JsonConvert.SerializeObject(new ResultModel(Response.StatusCode, "data"));
            //return JsonConvert.SerializeObject(new ResultModel(Response.StatusCode, "封装统一返回数据格式", "data"));
            //return JsonConvert.SerializeObject(new ResultModel(200, "获取全部用户信息", "data", new ResultModel.Cursor(100,10,10)));
        }

        /// <summary>
        /// 测试邮件
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<string> Email()
        {
            //MailMessage msg = new MailMessage();
            //msg.Subject = "测试";   //标题
            //msg.Body = " 测试,测试";    //内容
            //msg.From = new MailAddress("lllsss629@163.com");
            //msg.To.Add("1960681385@qq.com");
            //SmtpClient client = new SmtpClient();
            //client.Host = "smtp.163.com";   //发件方服务器地址
            //client.Port = 25;  //发件方端口
            //NetworkCredential credential = new NetworkCredential("lllsss629", "QEZMXXBBUQJUFEWL");
            //client.Credentials = credential;
            //client.Send(msg);

            //var requestPath = new RequestPath();
            //requestPath.PathBase = Request.PathBase.ToString();
            //requestPath.Host = Request.Host.ToString();
            //requestPath.IsHttps = Request.IsHttps;
            //requestPath.Scheme = Request.Scheme;
            //requestPath.Method = Request.Method;

            //var emailData = new Email("Testing1");
            ////emailData.RequestPath = requestPath;
            //emailData.ViewData["to"] = "1960681385@qq.com";
            //emailData.ViewData["Name"] = "Lesan";

            //await _emailService.SendAsync(emailData);

            //BackgroundJob.Schedule(() => NotifyNewLoginAsync(1), TimeSpan.FromMinutes(2));

            return JsonConvert.SerializeObject("");
        }

        /// <summary>
        /// 测试RabbitMQ发送方
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        [HttpGet]
        public string Rabbit(string message)
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var conn = factory.CreateConnection())
            using (var channel = conn.CreateModel())
            {
                channel.QueueDeclare(queue: "hello",
                                     durable: false,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);
                var body = Encoding.UTF8.GetBytes(message);
                channel.BasicPublish(exchange: "",
                                     routingKey: "hello",
                                     basicProperties: null,
                                     body: body);
            }
            return JsonConvert.SerializeObject("发送完成");
        }

        /// <summary>
        /// 测试使用特性来控制异常处理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandleException("WTF")]
        public IActionResult TestException()
        {

            int i = 0, j = 0;
            double s = i / j;
            //throw new System.Exception("123");

            return Json("123");
        }

    }
}
